<?php
/**
 * User: 784855684@qq.com
 * Date: 31/12/2017
 * Time: 13:19
 */
declare(strict_types=1);


namespace AppBundle\Controller;

use AppBundle\Entity\Material;
use AppBundle\Entity\MaterialOrder;
use AppBundle\Repository\MaterialOrderRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\OptimisticLockException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MaterialOrderController extends DefaultController
{

    /**
     * @Route("/material_order/overview", name="material_order_overview")
     * @return Response
     */
    public function overviewAction()
    {
        $em = $this->getDoctrine()->getManager();
        /** @var MaterialOrderRepository $repos */
        $repos = $em->getRepository(MaterialOrder::class);
        /** @var MaterialOrder[] $orders */
        $orders = $repos->findAllAvailable();
        $list = [];
        foreach ($orders as $order) {
            $material = $order->getMaterial();
            $createat = $order->getCreateAt()->format('Y-m-d H:i:s');
            $finishat = $order->getFinishAt();
            $list[] = [
                'oid' => $order->getId(),
                'material_name' => $material->getName(),
                'create_at' => $createat,
                'finish_at' => $finishat ? $finishat->format('Y-m-d H:i:s') : '',
                'number' => $order->getNumber(),
            ];
        }
        return $this->render('material_order/overview.html.twig', [
            'list' => $list,
        ]);
    }

    /**
     * @Route("/material/order/create")
     * @param Request $request
     * @return Response
     */
    public function createAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $material = $this->findMaterialOrResponseError($request->request->get('mid'));

        $order = new MaterialOrder();
        $order->setNumber((int)$request->request->get('number'));
        $order->setCreateAt(new \DateTime());
        $order->setMaterial($material);

        $em->persist($order);
        $em->flush();

        return $this->responseSuccess('Material order create success');
    }

    /**
     * @Route("/material/order/finish")
     * @param Request $request
     * @return JsonResponse
     * @throws \Doctrine\DBAL\ConnectionException
     */
    public function finishAction(Request $request)
    {
        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();
        $con = $em->getConnection();
        $con->beginTransaction();

        $order = $this->findMaterialOrderOrResponseError($request->request->get('oid'));
        $material = $order->getMaterial();

        $order->setFinishAt(new \DateTime());
        $material->setInventory($material->getInventory() + $order->getNumber());

        try {
            $em->flush();
            $con->commit();
            return $this->responseSuccess('Finish success');
        } catch (OptimisticLockException $exception) {
            $con->rollback();
            return $this->responseError(5001, "System error! Please retry again later.");
        }
    }

}